<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {//http post
    if ($action=='reg') {
        $pass1=trim($_POST['userpass']);
        $pass2=trim($_POST['reuserpass']);
        $has_error=false;
        if (empty($pass1)) {
            SfNotice::push('密码不能为空');
            $has_error=true;
        } else if ($pass1!=$pass2) {
            SfNotice::push('两次密码输出不一致');
            $has_error=true;
        } else {
            $attrs=array(   
                    'username'=>$_POST['username'],
                    'usernick'=>$_POST['usernick'],
                    'email'=>$_POST['email'],
                    );
            $status=$objUser->add($pass1,$attrs);
            switch($status) {
                case SfUser::STATUS_LOGIN_EXISTS:
                    SfNotice::push('用户名已经存在了');
                    $has_error=true;
                    break;
                case SfUser::STATUS_INVALID_LOGIN:
                    SfNotice::push('用户名必须为两位到十位的英文或者数字');
                    $has_error=true;
                    break;
                case SfUser::STATUS_ADD_OK:
                    break;
                default:
                    SfNotice::push('发生错误，请重新提交');
                    $has_error=true;
            }
        }
        if ($has_error) {
            redirect(cg('www_root').'reg');
        } else {
            $objUser->tryLogin($_POST['username'],$_POST['userpass']);
            //SfNotice::push('注册成功');
            redirect('http://'.$attrs['username'].'.'.cg('domain_name').'/');
        }
    } elseif ($action=='login') {
        $status=$objUser->tryLogin($_POST['username'],$_POST['userpass']);
        switch($status) {
            case SfUser::LOGIN_STATUS_LOGIN_NOT_EXISTS:
                SfNotice::push('用户不存在');
                break;
            case SfUser::LOGIN_STATUS_WRONG_PASSWORD:
                SfNotice::push('密码错误');
                break;
            default:
        }
        if ($status==SfUser::LOGIN_STATUS_OK) {
            if (!empty($_REQUEST['return_to'])) {
                redirect($_REQUEST['return_to']);
            } else {
                redirect('http://'.$_SESSION['username'].'.'.cg('domain_name').'/');
            }
        } else {
            redirect(cg('www_root').'login?return_to='.urlencode(@$_REQUEST['return_to']));
        }
    } elseif ($action=='logout') {
        $objUser->logout();
        if (!empty($_REQUEST['return_to'])) {
            redirect($_REQUEST['return_to']);
        } else {
            redirect(cg('www_root'));
        }
    }
} else if (
        $_SERVER['REQUEST_METHOD']=='GET'
        || $_SERVER['REQUEST_METHOD']=='HEAD'
        ) {//http get
    if ($action=='logout') {
        $objUser->logout();
        if (!empty($_REQUEST['return_to'])) {
            redirect($_REQUEST['return_to']);
        } else {
            redirect(cg('www_root'));
        }
    }
}
